package cinescope2014.boundaries;

import cinescope2014.utilities.Globale;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author pascal
 */
public class JIFApprecierCRUD extends javax.swing.JInternalFrame {

    private Connection icn;
    private DefaultTableModel idtm;
    private Map<String, String> imapFilms;
    private Map<String, String> imapMedia;
    private Map<String, String> imapAppreciations;

    /**
     * Creates new form JIFApprecierCRUD
     */
    public JIFApprecierCRUD() {
        initComponents();

        setTitle("CRUD Apprécier");

        try {
            // --- Connexion
            icn = Globale.getConnexion();

            String lsSQL;

            PreparedStatement lpst;
            ResultSet lrs;
            StringBuilder lsbSelect = new StringBuilder();
            //lsbSelect.append("SELECT * FROM apprecier ");
            lsbSelect.append("SELECT titre_film, nom_media, libelle_appreciation ");
            lsbSelect.append(" FROM film NATURAL JOIN media NATURAL JOIN apprecier NATURAL JOIN appreciation");

            lpst = icn.prepareStatement(lsbSelect.toString());
            lrs = lpst.executeQuery();

            Object[] tLigne;

            idtm = (DefaultTableModel) jTableApprecier.getModel();

            while (lrs.next()) {
                tLigne = new Object[3];

                tLigne[0] = lrs.getString(1);
                tLigne[1] = lrs.getString(2);
                tLigne[2] = lrs.getString(3);

                idtm.addRow(tLigne);
            }

            lrs.close();
            lpst.close();

            // Les media
            imapMedia = new HashMap<>();

            lsSQL = "SELECT id_media, nom_media FROM media";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();
            while (lrs.next()) {
                imapMedia.put(lrs.getString(2), lrs.getString(1));
                jComboBoxMedia.addItem(lrs.getString(2));
            }
            lrs.close();
            lpst.close();

            // Les films
            imapFilms = new HashMap<>();
            lsSQL = "SELECT id_film, titre_film FROM film";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();
            while (lrs.next()) {
                imapFilms.put(lrs.getString(2), lrs.getString(1));
                jComboBoxFilms.addItem(lrs.getString(2));
            }
            lrs.close();
            lpst.close();

            // Les appréciations
            imapAppreciations = new HashMap<>();
            lsSQL = "SELECT id_appreciation, libelle_appreciation FROM appreciation";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();
            while (lrs.next()) {
                imapAppreciations.put(lrs.getString(2), lrs.getString(1));
                jComboBoxAppreciations.addItem(lrs.getString(2));
            }
            lrs.close();
            lpst.close();

            jLabelMessage.setText("Okay !!!");

        } catch (SQLException ex) {
            jLabelMessage.setText(ex.getMessage());
        }

        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableApprecier = new javax.swing.JTable();
        jLabelMessage = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jComboBoxMedia = new javax.swing.JComboBox();
        jButtonAjouter = new javax.swing.JButton();
        jButtonSupprimer = new javax.swing.JButton();
        jButtonModifier = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jComboBoxFilms = new javax.swing.JComboBox();
        jComboBoxAppreciations = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jTableApprecier.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Film", "Media", "Appréciation"
            }
        ));
        jTableApprecier.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableApprecierMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableApprecier);

        jLabelMessage.setText("Message");

        jLabel6.setText("Media");

        jButtonAjouter.setText("Ajouter");
        jButtonAjouter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAjouterActionPerformed(evt);
            }
        });

        jButtonSupprimer.setText("Supprimer");
        jButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSupprimerActionPerformed(evt);
            }
        });

        jButtonModifier.setText("Modifier");
        jButtonModifier.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifierActionPerformed(evt);
            }
        });

        jLabel5.setText("Film");

        jLabel2.setText("Appréciation");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jLabelMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonAjouter)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonModifier)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonSupprimer))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel2))
                        .addGap(46, 46, 46)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jComboBoxAppreciations, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jComboBoxMedia, 0, 182, Short.MAX_VALUE)
                            .addComponent(jComboBoxFilms, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(26, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jComboBoxFilms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jComboBoxMedia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxAppreciations, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAjouter)
                    .addComponent(jButtonSupprimer)
                    .addComponent(jButtonModifier))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabelMessage)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        //
    }//GEN-LAST:event_formInternalFrameClosing

    private void jButtonAjouterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAjouterActionPerformed
        //
        try {
            String lsSQL;
                lsSQL = "INSERT INTO apprecier(id_film, id_media, id_appreciation) VALUES(?,?,?)";
            PreparedStatement lpst = icn.prepareStatement(lsSQL);

            lpst.setString(1, imapFilms.get(jComboBoxFilms.getSelectedItem().toString()));
            lpst.setString(2, imapMedia.get(jComboBoxMedia.getSelectedItem().toString()));
            lpst.setString(3, imapAppreciations.get(jComboBoxAppreciations.getSelectedItem().toString()));
//            System.out.println(jComboBoxDepartements.getSelectedItem().toString());
            lpst.executeUpdate();
            icn.commit();
            lpst.close();
            // Mise a jour de la jTable via le DTM
            String[] tLigne = new String[3];
            tLigne[0] = jComboBoxFilms.getSelectedItem().toString();
            tLigne[1] = jComboBoxMedia.getSelectedItem().toString();
            tLigne[2] = jComboBoxAppreciations.getSelectedItem().toString();
            idtm.addRow(tLigne);

            jLabelMessage.setText("Okay !!!");

        } catch (SQLException e) {
            jLabelMessage.setText("KO !!!!");
            System.out.println(e.getMessage());
        }
    }//GEN-LAST:event_jButtonAjouterActionPerformed

    private void jTableApprecierMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableApprecierMouseClicked
        //
        int liLigne = jTableApprecier.getSelectedRow();

        jComboBoxFilms.setSelectedItem(jTableApprecier.getValueAt(liLigne, 0).toString());
        jComboBoxMedia.setSelectedItem(jTableApprecier.getValueAt(liLigne, 1).toString());
        jComboBoxAppreciations.setSelectedItem(jTableApprecier.getValueAt(liLigne, 2).toString());
    }//GEN-LAST:event_jTableApprecierMouseClicked

    private void jButtonSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSupprimerActionPerformed
        //
        if (jTableApprecier.getSelectedRow() == -1) {
            jLabelMessage.setText("Vous devez sélectionner une ligne !!!");
        } else {

            try {
                String lsSQL;
                lsSQL = "DELETE FROM apprecier WHERE id_film=? AND id_media=?";
                PreparedStatement lpst = icn.prepareStatement(lsSQL);

                lpst.setString(1, imapFilms.get(jComboBoxFilms.getSelectedItem().toString()));
                lpst.setString(2, imapMedia.get(jComboBoxMedia.getSelectedItem().toString()));

                lpst.executeUpdate();
                icn.commit();
                lpst.close();
                // Suppression dans la jTable via le DefalutTableModel
                idtm.removeRow(jTableApprecier.getSelectedRow());

                jLabelMessage.setText("Okay !!!");

            } catch (SQLException e) {
                jLabelMessage.setText("KO !!!!");
                System.out.println(e.getMessage());
            }

        }
    }//GEN-LAST:event_jButtonSupprimerActionPerformed

    private void jButtonModifierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifierActionPerformed
        // 
//        int liLigne = jTableApprecier.getSelectedRow();
//        if (liLigne == -1) {
//            jLabelMessage.setText("Vous devez sélectionner une ligne !!!");
//        } else {
//
//            try {
//                PreparedStatement lpst = icn.prepareStatement("UPDATE journaliste SET nom_journaliste=?, id_media=? WHERE id_journaliste=?");
//
//                lpst.setString(1, jTextFieldNom.getText());
//                lpst.setString(2, imapMedia.get(jComboBoxMedia.getSelectedItem().toString()));
//                lpst.setString(3, jLabelID.getText());
//
//                lpst.executeUpdate();
//
//                // Modification dans la jTable
////                jTableVilles.setValueAt(jTextFieldCP.getText(), liLigne, 1);
////                jTableVilles.setValueAt(jTextFieldNom.getText(), liLigne, 2);
////                jTableVilles.setValueAt(jComboBoxDepartements.getSelectedItem(), liLigne, 3);
//
//                idtm.setValueAt(jLabelID.getText(), liLigne, 0);
//                idtm.setValueAt(jTextFieldNom.getText(), liLigne, 1);
//                idtm.setValueAt(jComboBoxMedia.getSelectedItem(), liLigne, 2);
//
//                jLabelMessage.setText("Okay !!!");
//
//            } catch (SQLException e) {
//                jLabelMessage.setText("KO !!!!");
//                System.out.println(e.getMessage());
//            }

//        }
    }//GEN-LAST:event_jButtonModifierActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAjouter;
    private javax.swing.JButton jButtonModifier;
    private javax.swing.JButton jButtonSupprimer;
    private javax.swing.JComboBox jComboBoxAppreciations;
    private javax.swing.JComboBox jComboBoxFilms;
    private javax.swing.JComboBox jComboBoxMedia;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableApprecier;
    // End of variables declaration//GEN-END:variables
}
